/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package emailer;

import com.openbrew.openbrewrf.Administration;
import com.openbrew.openbrewrf.Employee;
import com.openbrew.openbrewrf.SalesOrder;
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import pdf.SOPDFCreator;
import view.CreateSimpleSalesOrderView;
import view.SimpleSalesOrderView;

/**
 *
 * @author chapmand
 */
public class SalesOrderEmailer {
    private ByteArrayOutputStream outputStream = null;
    
    public void sendMail(final EntityManager en, final SalesOrder salesOrderID){
        final Administration admin = getAdmin(en);
        final SOPDFCreator sopdf = new SOPDFCreator();
        CreateSimpleSalesOrderView createView = new CreateSimpleSalesOrderView();
        final SimpleSalesOrderView simpleSalesOrderView = createView.getSalesOrderString(salesOrderID, admin);
        
        outputStream = new ByteArrayOutputStream();
        sopdf.createPDF(outputStream, salesOrderID, simpleSalesOrderView, admin);
        byte[] bytes = outputStream.toByteArray();
        
        Employee emp = admin.getSalesEmp();
        
        final String username = admin.getBillingEmail();
        final String password = admin.decryptBillingEmailPassword();
        final String ccAddress = emp.getEmpEmail();
        
        final String fname = "Invoice " + salesOrderID.getSOId() + ".pdf";
        
        Properties props = new Properties();
        if(admin.getSMTPAuth()){
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }
        
        if(admin.getSMTPStartTls()){
            props.put("mail.smtp.starttls.enable", "true");
        } else {
            props.put("mail.smtp.starttls.enable", "false");
        }
        props.put("mail.smtp.host", admin.getSMTPAddress());
        props.put("mail.smtp.port", admin.getSMTPPort());
        
        Session session = Session.getInstance(props,
              new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                    }
              });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(admin.getBillingEmail()));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(salesOrderID.getSOCust().getCEmail()));
            //Set any CC Addresses.
            if(!salesOrderID.getSOCust().getCEmailCC().isEmpty()){
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(salesOrderID.getSOCust().getCEmailCC()));
            }

            message.setSubject(admin.getBillingEmailSubject());
            if(!ccAddress.isEmpty()){
                message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddress));
            }

            //Create Message Part
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(admin.getBillingEmailBody());

            //Create a multipar message
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            //Part two is attachement.
            messageBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
            messageBodyPart.setDataHandler(new DataHandler(dataSource));
            messageBodyPart.setFileName(fname);
            
            multipart.addBodyPart(messageBodyPart);
            

            //Send the complete message parts.
            message.setContent(multipart);

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
    
    /***************************************************************************
     * Database modification functions.
     **************************************************************************/
    private Administration getAdmin(final EntityManager en){
        TypedQuery<Administration> query = en.createQuery(
            "SELECT a FROM Administration a WHERE a.aNum = '1'", Administration.class);
        Administration admin = query.getSingleResult();
        return admin;
    }
    
}
